import { getTempId } from "@/utils/userTempId";
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
import {
  getToken,
  setToken,
  removeToken,
  setSessionToken,
  getSessionToken,
  removeSessionToken,
} from "@/utils/token";
const state = {
  // userTempId: "001",
  userTempId: getTempId(),
  token: getToken() || getSessionToken() || "",
  userInfo: {},
};
const mutations = {
  //设置token
  SET_TOKEN(state, payload) {
    state.token = payload.token;
    if (payload.autoLogin) {
      //一旦重新修改token,则要在本地存储一份
      setToken(payload.token);
    } else {
      //在临时存储之前删除永久存储
      removeToken();
      //临时存储
      setSessionToken(payload.token);
    }
  },
  //设置用户信息
  SET_USERINFO(state, payload) {
    state.userInfo = payload.userInfo;
  },
  //清空用户信息和token
  CLEAR_USER(state) {
    state.token = "";
    state.userInfo = "";
    removeToken();
    removeSessionToken();
  },
};
const actions = {
  //获取token
  async getToken({ commit }, payload) {
    try {
      //接收来自组件的autoLogin
      const autoLogin = payload.autoLogin;
      const result = await reqLogin(payload);
      //提交mutations的时候,把autoLogin也提交出去
      commit("SET_TOKEN", { token: result.token, autoLogin });
    } catch (e) {
      return Promise.reject(e);
    }
  },
  //获取userInfo
  async getUserInfo({ commit }) {
    try {
      const result = await reqUserInfo();
      commit("SET_USERINFO", { userInfo: result });
    } catch (e) {
      return Promise.reject(e);
    }
  },
  //退出登录
  async getLogout({ commit }) {
    try {
      await reqLogout();
      commit("CLEAR_USER");
    } catch (e) {
      return Promise.reject(e);
    }
  },
};
const getters = {};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
